<?php
class PenerimaanTamuController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column1', meaning
	 * using one-column layout. See 'protected/views/layouts/column1.php'.
	 */
	public $layout='//layouts/column1';
        
        private $notifikasiValue = "";

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'rights',
		);
	}

	public function allowedActions() 
        { 
            //return ''; 
        }
        
        public function actions()
        {
            return array(
                'jpegcam.'=> array(
                    'class'=>'application.extensions.jpegcam.EJpegcam',
                    'saveJpg'=>array(
                        'filepath'=> Yii::app()->basePath . "/../images/photos/temp/". strtotime(date('Y-m-d h:i:s')).".jpg" // This could be whatever
                    )
                )
            );
        }
        
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
            $PenerimaanTamu = $this->loadModel($id);
            
            $this->render('view',array(
                    'PenerimaanTamu'=>$PenerimaanTamu,
            ));
	}

        public function actionExpressCreate(){
            
            $PenerimaanTamu = new PenerimaanTamu;
		$Tamu		= new Tamu;
		$Meetingroom	= new Meetingroom;
		$Pegawai	= new Pegawai;  
		$Jabatan	= new Jabatan;
		$JenisKeperluan = new JenisKeperluan;
                $JenisKegiatan  = new JenisKegiatan;
                $Instansi       = new Instansi;

		// Uncomment the following line if AJAX validation is needed
 		 $this->performAjaxValidation($PenerimaanTamu);
                 
                 $this->performAjaxValidation($Tamu);
                 $this->performAjaxValidation($Pegawai);
                 $this->performAjaxValidation($Instansi);
                 $this->performAjaxValidation($JenisKegiatan);
                 $this->performAjaxValidation($JenisKeperluan);

		if(!empty($_POST))
		{
                    $this->debug($_POST);
			//$PenerimaanTamu->attributes=$_POST['PenerimaanTamu'];
			//if($PenerimaanTamu->save())
			//	$this->redirect(array('view','id'=>$PenerimaanTamu->id_penerimaan_tamu));
		}

		$this->render('express_create',array(
			'PenerimaanTamu'=>$PenerimaanTamu,
			'Tamu' => $Tamu,
                        'Instansi' => $Instansi,
			'Meetingroom' => $Meetingroom,
			'Pegawai' => $Pegawai,
			'Jabatan' => $Jabatan,
                        'JenisKegiatan' => $JenisKegiatan,
                        'JenisKeperluan'  => $JenisKeperluan,
                        'host' => CHttpRequest::getUserHostAddress()
		));
            
        }
        
        public function actionListByUser()
        {
                $model=new PenerimaanTamu('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['PenerimaanTamu']))
			$model->attributes = $_GET['PenerimaanTamu'];

		$this->render('ListByUser',array(
			'model'=>$model,
                        'Tamu' => new Tamu,
                        'Pegawai' => new Pegawai
		));
        }
        
        public function actionAccept($id_penerimaan_tamu, $url=null){
            
            $PenerimaanTamu = PenerimaanTamu::model()->findByPk($id_penerimaan_tamu);
            $Meetingroom    = Meetingroom::model()->findByPk($_POST['Meetingroom']['id_meetingroom']);
            $PemakaianMeetingroom = new PemakaianMeetingroom;
            
            $_POST['PemakaianMeetingroom']['mulai'] = date('Y-m-d ').$_POST['PemakaianMeetingroom']['mulai'];
            $_POST['PemakaianMeetingroom']['akhir'] = date('Y-m-d ').$_POST['PemakaianMeetingroom']['akhir'];
           
            $transaction = Yii::app()->db->beginTransaction();
                    
            try{
              
                //Jadwal Pemakaian Meeting Room
                $PemakaianMeetingroom->attributes = $_POST['PemakaianMeetingroom'];
                $PemakaianMeetingroom->keterangan = "Penerimaan tamu ".$PenerimaanTamu->Tamu->nama." dari "
                                                    .$PenerimaanTamu->Tamu->Instansi->nama." oleh ".$PenerimaanTamu->Pegawai->nama;
                $PemakaianMeetingroom->id_pegawai = Yii::app()->user->id;
                $PemakaianMeetingroom->id_meetingroom = $_POST['Meetingroom']['id_meetingroom'];
                $PemakaianMeetingroom->save();
                
                $notifikasi = new PesanNotifikasi;
                $notifikasi->url = '';
                $notifikasi->notifikasi = "Tamu dengan nama ".$PenerimaanTamu->Tamu->nama." dari "
                                            .$PenerimaanTamu->Tamu->Instansi->nama." 
                                           telah diterima dan dipersilahkan tunggu di ruang ".$PemakaianMeetingroom->Meetingroom->nama.", "
                                            .$PemakaianMeetingroom->Meetingroom->lokasi;
                $notifikasi->id_group = 1;
                $notifikasi->created_date = date('Y-m-d H:i:s');
                $notifikasi->save();
                
                $PenerimaanTamu->status_terima  = 1;
                $PenerimaanTamu->aktual_mulai   = date('Y-m-d H:i:s');
                $PenerimaanTamu->save();
                
                $transaction->commit();
                
            } 
            catch (Exception $e)
            {
                $this->debug($e);
                $transaction->rollback(); // rollback transaction
                
            }
            
            
            
            if($url==null)
                $url = Yii::app()->createUrl('PenerimaanTamu/listbyuser');
                
            $this->redirect($url);
        }
        
        /**
         * @param Int $id_penerimaan_tamu 
         */
        public function actionViewDetail($id_penerimaan_tamu)
        {
            $PenerimaanTamu = PenerimaanTamu::model()->with(
                                'Pegawai', 'Tamu', 
                                'KartuTamu', 'Keperluan'
                                )->findByPk($id_penerimaan_tamu);
            $Identitas      = Identitas::model()->findByAttributes(array('id_tamu'=>$PenerimaanTamu->Tamu->id_tamu));
            $Meetingroom    = new Meetingroom;
            
            $this->render('ViewDetail',
                    array(
                        'PenerimaanTamu' => $PenerimaanTamu,
                        'Identitas' => $Identitas,
                        'Meetingroom' => $Meetingroom
                    ));
        }

        /**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$PenerimaanTamu = new PenerimaanTamu;
		$Tamu		= new Tamu;
		$Meetingroom	= new Meetingroom;
		$Pegawai	= new Pegawai;
		$Jabatan	= new Jabatan;
		$JenisKeperluan = new JenisKeperluan;
                $JenisKegiatan  = new JenisKegiatan;
                $Instansi       = new Instansi;
                $Identitas      = new Identitas;

		// Uncomment the following line if AJAX validation is needed
 		 $this->performAjaxValidation($PenerimaanTamu);
                 
                 $this->performAjaxValidation($Tamu);
                 $this->performAjaxValidation($Pegawai);
                 $this->performAjaxValidation($Instansi);
                 $this->performAjaxValidation($JenisKegiatan);
                 $this->performAjaxValidation($JenisKeperluan);

		if(!empty($_POST))
		{
                   //$this->debug($_POST); die;
                   $transaction = Yii::app()->db->beginTransaction();
                    
                   try{
                        
                        $Tamu->attributes = $_POST['Tamu'];
                        $Instansi->attributes = $_POST['Instansi'];
                        $JenisKeperluan->attributes =   $_POST['JenisKeperluan'];

                        if($_POST['Instansi']['id_instansi']=='')
                            $Instansi->save(); // saving if isnt exist
                        
                        $Tamu->id_instansi = $Instansi->id_instansi;
                        
                        //Tamu baru
                        if($_POST['Tamu']['id_tamu']=='')
                        {
                            if($Tamu->save()) // save
                            {
                                if (Yii::app()->file->set('images/photos/temp/'.$Tamu->foto)->exists)
                                {
                                    $fotoTemp   = Yii::app()->file->set('images/photos/temp/'.$Tamu->foto, true);
                                    $copyFoto  = $fotoTemp->copy('images/photos/'.$Tamu->foto);
                                    if($copyFoto)
                                    {
                                        $fotoTemp->delete();
                                    }
                                }
                            }
                        }else{
                            //tamu yang sudah terdaftar
                            $Tamu = Tamu::model()->findByPk($_POST['Tamu']['id_tamu']);
                            Identitas::model()->deleteAllByAttributes(
                                    array(
                                        'id_tamu' => $Tamu->id_tamu
                                    ));

                        }
                            
                        if($_POST['JenisKeperluan']['id_keperluan']=="")
                        {
                            $JenisKeperluan->save();
                        }
                        
                        foreach($_POST['no_identitas'] as $key=>$value)
                        {
                            $Identitas = new Identitas;
                            $Identitas->no_identitas    = $_POST['no_identitas'][$key];
                            $Identitas->tipe_identitas  = $_POST['tipe_identitas'][$key];
                            $Identitas->id_tamu         = $Tamu->id_tamu;
                            if($Identitas->save())
                                $Identitas->id_identitas = NULL;
                        }
                        
                        $PenerimaanTamu->attributes = $_POST['PenerimaanTamu'];
                        $PenerimaanTamu->id_tamu    = $Tamu->id_tamu;
                        $PenerimaanTamu->status_terima = 'Menunggu';
                        $PenerimaanTamu->tanggal    = date('Y-m-d'); //2012-11-04
                        $PenerimaanTamu->jam_datang = date('Y-m-d H:i:s'); //2012-11-04 01:35:42
                        $PenerimaanTamu->id_keperluan = $JenisKeperluan->id_keperluan;
                        
                        $PenerimaanTamu->save();
                        
                        $noKartu = KartuTamu::model()->findByPk($_POST['PenerimaanTamu']['id_kartu_tamu']);
                        $noKartu->status = 0;
                        $noKartu->save();
                        
                        // kirim pesan ke pegawai melalui sms/email/
                        // Email Start
                        
                        // SMS Start
                        
                        // Notifikasi Start
                        $notifikasi = new PesanNotifikasi;
                        $notifikasi->url = Yii::app()->createUrl('/PenerimaanTamu/listbyuser');
                        $notifikasi->notifikasi = "Saat ini tamu dengan nama ".$Tamu->nama." dari ".$Instansi->nama." datang hari ini igin bertemu anda";
                        $notifikasi->id_pegawai = $_POST['PenerimaanTamu']['id_pegawai'];
                        $notifikasi->created_date = date('Y-m-d H:i:s');
                        $notifikasi->save();
                        
                        
                        $transaction->commit(); // commit transaction
                        
                        $this->redirect(array('index'));
                        
                    }  catch (Exception $e){
                        
                        $transaction->rollback(); // rollback transaction
                        
                        //$this->debug($e);
                        //die;
                    }
                    
		}

		$this->render('create',array(
			'PenerimaanTamu'=>$PenerimaanTamu,
			'Tamu' => $Tamu,
                        'Instansi' => $Instansi,
			'Meetingroom' => $Meetingroom,
			'Pegawai' => $Pegawai,
			'Jabatan' => $Jabatan,
                        'JenisKegiatan' => $JenisKegiatan,
                        'JenisKeperluan'  => $JenisKeperluan,
                        'Identitas' => $Identitas
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['PenerimaanTamu']))
		{
			$model->attributes=$_POST['PenerimaanTamu'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id_penerimaan_tamu));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new PenerimaanTamu('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['PenerimaanTamu']))
			$model->attributes = $_GET['PenerimaanTamu'];

		$this->render('index',array(
			'model'=>$model,
                        'Tamu' => new Tamu,
                        'Pegawai' => new Pegawai
		));
	}

	/**
	 * Auto complete
	 */
	public function actionAutocomplete () {
		  if (isset($_GET['term'])) {
		  	 
		    $criteria=new CDbCriteria;
		    $criteria->condition = "nama like '" . $_GET['term'] . "%'";
		
		    $dataProvider = new CActiveDataProvider(get_class(Tamu::model()), array(
			'criteria'  =>  $criteria, 
                        'pagination'    =>  false,
			));
		    $tamu = $dataProvider->getData();
                    
		    $return_array = array();
		    foreach($tamu as $value) {
		      $return_array[] = array(
		                    'label'=>$value->nama,
		                    'value'=>$value->nama,
                                    'alamat' => $value->alamat,
                                    'no_identitas' => $value->no_identitas,
                                    'jenis_identitas'=> $value->jenis_identitas,
                                    'desc' => 'sss',
                                    'no_telp'=> $value->no_telp,
		                    'foto' => Yii::app()->request->baseUrl.'/images/photos/'.$value->foto,
		                    'id'=>$value->id_tamu,
		                    );
		    }
		
		    echo CJSON::encode($return_array);
		  }
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=PenerimaanTamu::model()->with(
                        'Tamu', 'Meetingroom', 
                        'Pegawai', 'KartuTamu',
                        'Keperluan'
                        )->findByPk($id);
                
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='penerimaan-tamu-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
